import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import md5 from 'js-md5';
import {
  VueAxios
} from './axios'
import {
  ACCESS_TOKEN,
  DEFAULT_SITE
} from '@/store/mutation-types'
//import { getDefault } from '@/api/site/site'
// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 25000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403 || error.response.status === 503) {
      notification.error({
        message: '认证异常!',
        description: data.msg
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: '授权登录失败',
        description: (data.msg ? data.msg : '请检查账户密码是否正确')
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          console.log('------退出系统-----------')
        })
      }
      setTimeout(() => {
        window.location.reload()
      }, 1500)
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = 'bearer  ' + token
    config.headers[DEFAULT_SITE] = getSite()
  }
  var appid = '2E2U3Y3NGXAE1QCU';
  var timeStamp = new Date().getTime().toString()
  var nonceStr = generateMixed(8)
  config.headers['appid'] = appid;
  config.headers['timeStamp'] = timeStamp
  config.headers['nonceStr'] = nonceStr
  config.headers['sign'] = md5(nonceStr + timeStamp + appid).toLowerCase()
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  if (response.config.responseType === 'blob') {
    return response
  }
  if (response.data && response.data.code === 5022) {
    notification.warn({
      message: '警告!',
      description: '默认站点没有设置'
    })
  }
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}


const setSite = function setSite(siteId) {
  storage.set(DEFAULT_SITE, siteId)
}

const getSite = function getSite() {
  let siteId = storage.get(DEFAULT_SITE)
  if (!siteId) {
    siteId = ""
  }
  return siteId
}


export default request

export {
  installer as VueAxios,
  request as axios,
  setSite,
  getSite
}

function generateMixed(n) {
  var chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
  var res = ""
  for (var i = 0; i < n; i++) {
    var id = Math.ceil(Math.random() * 62);
    res += chars[id];
  }
  return res;
}